package com.bytecub.udp.service.parser;

import com.bytecub.common.enums.BCErrorEnum;
import com.bytecub.common.exception.BCGException;
import com.bytecub.protocol.domain.bo.DeviceProductBo;
import com.bytecub.protocol.service.IProtocolUtilService;
import com.bytecub.udp.domain.bo.ParseDeviceBo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * * ByteCub.cn. * Copyright (c) 2020-2021 All Rights Reserved. * 定位到产品 * @author bytecub@163.com
 * songbin * @Date 2021/4/2 Exp $$
 */
@Slf4j
@Service
public class UdpProtocolParser {
    @Autowired IProtocolUtilService protocolUtilService;
    @Autowired HeaderParser headerParser;

    public ParseDeviceBo parseProtocol(byte[] content) {
        ParseDeviceBo parseDeviceBo = headerParser.parseBody(content);
        /** 获取当前上报数据设备编码 */
        String deviceCode = parseDeviceBo.getDeviceCode();
        /** 判断此条消息是否为管网设备在上报子设备数据 */
        Boolean subFlag = parseDeviceBo.getSubFlag();
        if (StringUtils.isEmpty(deviceCode)) {
            throw BCGException.genException(BCErrorEnum.INNER_EXCEPTION, "无法从原始报文解析得到设备编码");
        }
        DeviceProductBo deviceProductBo = protocolUtilService.queryInstanceByDeviceCode(deviceCode);
        if (null == deviceProductBo) {
            throw BCGException.genException(
                    BCErrorEnum.INNER_EXCEPTION, deviceCode + "无法找到对应的产品协议");
        }
        parseDeviceBo.setBaseProtocol(deviceProductBo.getBaseProtocol());
        parseDeviceBo.setDeviceCode(deviceCode);
        parseDeviceBo.setProductCode(deviceProductBo.getProductCode());
        return parseDeviceBo;
    }
}
